package cn.tsingyu.antsclub.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Service;

import cn.tsingyu.antsclub.bean.User;
import cn.tsingyu.antsclub.util.TimeUtil;

@Service
public class UserService{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void create(String name, Integer age) {
        //jdbcTemplate.update("insert into USER(uname, role) values(?, ?)", name, age);
    	String sql =" insert into verification(mobile, type, code, createTime) values(?,?,?,?) ";
    	jdbcTemplate.update(sql, "15950014490","register","1234",TimeUtil.getCurrentTime());
    }

    public void deleteByName(String name) {
        jdbcTemplate.update("delete from USER where uname = ?", name);
    }

    public Integer getAllUsers() {
        return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
    }

    public void deleteAllUsers() {
        jdbcTemplate.update("delete from USER");
    }

	public User findByUsername(String username) {
		final User user = new User();
		jdbcTemplate.query("SELECT * FROM user_info WHERE username = ?",new Object[] {username},
				new RowCallbackHandler() {  
                    public void processRow(ResultSet rs) throws SQLException {
                    	user.setUid(rs.getLong("uid"));
                        user.setUsername(rs.getString("username")); 
                        user.setPassword(rs.getString("password"));
                    }  
                });
		return user;
	}
	public Set<String> getPermission(long uid){
		final Set<String> permissions = new HashSet<String>();
		String sql = "select p.permission from sys_user_role ur "
					+" left join sys_role_permission rp "
					+" on ur.role_id=rp.role_id "
					+" left join sys_permission p on rp.permission_id=p.id "
					+" where ur.uid=?";
		
		jdbcTemplate.query(sql,new Object[] {uid},
				new RowCallbackHandler() {  
                    public void processRow(ResultSet rs) throws SQLException {
                    	permissions.add(rs.getString("permission"));
                    }  
                });
		return permissions;
	}
}
